///<reference path="../../enum/ServerEnum.ts"/>
/**
 * Created by PengWei on 2018/7/26.
 */
namespace mengdao {

    export class ServerGetter {

        /** 协议类型 */
        private _protocol: ProtocolType = ProtocolType.WS;
        /** 服务器ip */
        private _host: string;
        /** 服务器端口 */
        private _port: number;
        /** ipv4 \ ipv6 */
        private _ipVersion: IpVersionType = IpVersionType.IPV4;

        public set host(v: string) {
            this._host = v;
        }

        public set port(v: number) {
            this._port = v;
        }

        public set protocol(v: ProtocolType) {
            this._protocol = v;
        }

        public get protocol(): ProtocolType {
            return this._protocol;
        }

        public get isWSS():boolean{
            return this._protocol == ProtocolType.WSS;
        }

        public get host(): string {
            if (this._ipVersion == IpVersionType.IPV6) {
                if (this.isIpV6(this._host)) {
                    return this.packageIpv6(this._host);
                } else {
                    return this.ipv4ToIpv6(this._host);
                }
            }
            return this._host;
        }

        public get port(): number {
            return this._port;
        }

        private isIpV6(address: string) {
            if (!/^(?=\d+\.\d+\.\d+\.\d+$)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.?){4}$/.test(address)) {
                return true;
            }
            return false;
        }

        private packageIpv6(v6: string) {
            if (v6.indexOf("[") == -1)
                return "[" + v6 + "]";
            return v6
        }

        private ipv4ToIpv6(v4: string) {
            let ipSplitter = v4.split(".");
            let v4Array: string[] = [];

            for (let i = 0; i < 4; i++) {
                let ip10 = ipSplitter[i];
                let ip10Int = parseInt(ip10);
                let t = ip10Int.toString(16);
                t = ip10Int < 16 ? "0" + t : t;
                v4Array[i] = t;
            }

            let v6Array: string[] = ["0000", "0000", "0000", "0000", "0000", "0000", "0000", "0000"];
            v6Array[5] = "ffff";
            v6Array[6] = v4Array[0] + v4Array[1];
            v6Array[7] = v4Array[2] + v4Array[3];
            return "[" + v6Array.join(":") + "]";
        }
    }
}